#ifdef USE_SQL
#include <string.h>

#include "lib.h"
#include "bratserv.h"
#include "bratconn.h"
#include "brathand.h"
#include "bratsql.h"
#include "bratproto.h"
#include "stdncerr.h"
#include "opts.h"
#include "log.h"
#include "badpacketmsgs.h"

#include "XMLTranslator.h"

static BratSQL* tracker = (BratSQL*)0;

typedef struct _info
{
	String			login;
	PID				pid;
	SESSIONID		sessionId;
	bool8			forMoney;

	_info()
	{
		memset( sessionId, 0, sizeof(sessionId) );
		forMoney = false;
	}
} Info, *pInfo;

void
BratServer::startTracker()
{
	ServerOpts::load();

	tracker = new BratSQL(
		ServerOpts::dbdsn, ServerOpts::dblogin, ServerOpts::dbpasswd);

	// CSN-8891
	webServiceCall = new WebServiceCall();
}

void
BratServer::stopTracker()
{
	delete tracker;
	tracker = 0;

	delete webServiceCall;
	webServiceCall = 0;
}

bool8
BratServer::initSuccess()
{
	if (tracker && tracker->initOK())
		return Server::initSuccess();
	else
	{
		Log::msgError("Failed to connect to the database.  Aborting.");
		return false;
	}
}


bool8
BratConnection::parseCasinoLogin(int32 stdReq, int32* Err)
{
	Info *	info;
	char	login[PIDLEN + 1] = { 0 };
	int32	i;

	if (msgbuf[1]	!= APP1				|| msgbuf[2] != APP2 ||
		msgbuf[3]	!= PROTO_VERSION1	|| msgbuf[4] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		DEBUGMSG(("Login: incorrect version: %c%c  ",
				msgbuf[1],msgbuf[2],msgbuf[3],msgbuf[4]));
		return false;
	}

	info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	i = stdReq;

	memcpy(login, msgbuf + i, PIDLEN);
	login[PIDLEN] = 0;
	i += PIDLEN;

	strlwr(login);
	info->login = login;

	info->forMoney = (bool8)(msgbuf[i++] != 0);

	// CSN-10426: with this modification, we don't need iClientID sent by the client, so we skip it
	String sClientTypeIntAPI = String::emptyString;
	i++;	// Skip ClientID

	if (xmlTranslator && xmlTranslator->UsingFunPID())
	{
		// CSN-7076: New Authentication (fun play)
		bool8 result;
		tracker->lock();
		result = tracker->getAvailableFunID( info->login );
		tracker->unlock();
		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}
	else
	{	
		// CSN-7075: New Authentication
		String sToken = String::emptyString;
		i =+ sToken.deserialize(&msgbuf[i]);
		
		// CSN-8909: Look for clientType in Integration API
		if (!wsCall()->Authenticate(sToken, info->login, sClientTypeIntAPI, m_sCurrency))
		{
			bool8 bAuth = false;
			
			// CSN-12167: connect with no token? In that case, white-listed PID is sent in <Token> field
			#ifdef DEBUGSPIN
			if (ServerOpts::bAllowTesting)
			{
				bAuth = tracker->isFreeFromAuthentication(sToken);					
				if (bAuth)
					info->login = sToken;
			}
			#endif

			if (!bAuth)
			{
				*Err = LOGINERR_CONTACTCUSTSERVICE;
				delete info;
				info = 0;
				return false;
			}
		}
		
	}
	
	if (tracker)
	{
		//int32 result;
		bool8 result;

		tracker->lock();
		//result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		result = tracker->createRTGSession(info->forMoney, info->login, info->sessionId, sClientTypeIntAPI);
		tracker->unlock();

		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
		
	}

	info->pid = info->login;
	casinoSpecific = info;

    #ifdef FORCEDSHOE 
    m_pid=info->login;
    #endif


	return true;
}

bool8
BratConnection::parseUnicodeCasinoLogin(int32 stdReq, int32* Err)
{
	Info *	info;
	int32	i;

	if (msgbuf[2]	!= APP1				|| msgbuf[3] != APP2 ||
		msgbuf[4]	!= PROTO_VERSION1	|| msgbuf[5] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		DEBUGMSG(("Login: incorrect version: %c%c  ",
				msgbuf[2],msgbuf[3],msgbuf[4],msgbuf[5]));
		return false;
	}

	info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	i = stdReq;

	i += info->login.deserialize(msgbuf + i);
	info->login.toLower();

	info->forMoney = (bool8)(msgbuf[i++] != 0);

	// CSN-10426: with this modification, we don't need iClientID sent by the client, so we skip it
	String sClientTypeIntAPI = String::emptyString;
	i++;	// Skip ClientID

	if (xmlTranslator && xmlTranslator->UsingFunPID())
	{
		// CSN-7076: New Authentication (fun play)
		bool8 result;
		tracker->lock();
		result = tracker->getAvailableFunID( info->login );
		tracker->unlock();
		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}
	else
	{	
		// CSN-7075: New Authentication
		String sToken = String::emptyString;
		i =+ sToken.deserialize(&msgbuf[i]);
	
		// CSN-8909: Look for clientType in Integration API
		if (!wsCall()->Authenticate(sToken, info->login, sClientTypeIntAPI, m_sCurrency))
		{
			bool8 bAuth = false;
			
			// CSN-12167: connect with no token? In that case, white-listed PID is sent in <Token> field
			#ifdef DEBUGSPIN
			if (ServerOpts::bAllowTesting)
			{
				bAuth = tracker->isFreeFromAuthentication(sToken);					
				if (bAuth)
					info->login = sToken;
			}
			#endif

			if (!bAuth)
			{
				*Err = LOGINERR_CONTACTCUSTSERVICE;
				delete info;
				info = 0;
				return false;
			}
		}
	}
	
	if (tracker)
	{
		//int32 result;
		bool8 result;

		tracker->lock();
		//result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		result = tracker->createRTGSession(info->forMoney, info->login, info->sessionId, sClientTypeIntAPI);
		tracker->unlock();

		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			return false;
		}
		
	}
	info->pid = info->login;
	casinoSpecific = info;

    #ifdef FORCEDSHOE 
    m_pid=info->login;
    #endif


	return true;
}


void
BratConnection::removeCasinoSpecific()
{
	delete (pInfo)casinoSpecific;

	casinoSpecific = (void*)0;
}

int32
BratConnection::encode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
BratConnection::decode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

bool8
BratConnection::trackGetBalance( int32 *balance )
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = BratSQL::ExecFailed;
	int32 comp;
	*balance = 0;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->getBalance(ServerOpts::casinoId,
			info->pid, info->forMoney, balance, &comp);
		tracker->unlock();
	}

	return (bool8)(result == BratSQL::NoError);
}

int32
BratConnection::trackAdjustBalance(int32 Amount)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = BratSQL::ExecFailed;
	int32 bal=0, comp=0;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->adjustBalance(ServerOpts::casinoId,
			info->pid, info->forMoney, Amount, &bal, &comp);
		tracker->unlock();
	}

	if (result == BratSQL::NoError)
		return bal;
	return 0;
}

bool8
BratConnection::trackGetPlayerLimits(int32* minBet, int32* maxBet,
	int32* compFactor)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = BratSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->getPlayerLimits(info->pid, GAMEID, MACHID,
			minBet, maxBet, compFactor);
		tracker->unlock();
	}

	return (bool8)(result == BratSQL::NoError);
}

bool8
BratConnection::trackGame(BratHand* Bank, BratHand* Player,
	int32* Bets, int32* Payouts, int32 NumBetsPayouts,
	int32 Commission, int32 Outcome, int32 BalanceAdjust, int32* Balance)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = BratSQL::ExecFailed;
	int32 comp;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->game(ServerOpts::casinoId,
			info->pid, info->forMoney, info->sessionId,
			info->forMoney ? compFactor : 0,
			Bank->getCount(), Bank->getCards(),
			Player->getCount(), Player->getCards(),
			Bets, Payouts, NumBetsPayouts, Commission, Outcome, BalanceAdjust,
			Balance,
			&comp);
		tracker->unlock();
	}

	return (bool8)(result == BratSQL::NoError);
}

void
BratConnection::trackaddBadPacket(int32 error_reason, char MessageType, char *msgbuf, int32 msglen)
{
	pInfo info = (pInfo)casinoSpecific;

	if (tracker && info)
	{
		tracker->lock();
		tracker->addBadPacket(GAMEID, MACHID, sBadPacketMessages[error_reason].message, sBadPacketMessages[error_reason].severity, info->pid, MessageType, (uint8 *)msgbuf, msglen);
		tracker->unlock();
	}
}

bool8
BratConnection::trackGetOptions(int32 * tiePayout)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = BratSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->trackGetOptions(tiePayout);
		tracker->unlock();
	}

	return (bool8)(result == BratSQL::NoError);
}

int32
BratConnection::trackValidateLogin()
{
    pInfo info = (pInfo)casinoSpecific;
    int32 result = BratSQL::ExecFailed;

    if (tracker && info)
    {
        tracker->lock();
		result = tracker->validateLogin(info->login, info->sessionId, info->pid);
        tracker->unlock();
    }

    return result;
}

int32
BratConnection::trackValidateSession()
{
    pInfo info = (pInfo)casinoSpecific;
    int32 result = BratSQL::ExecFailed;

    if (tracker && info)
    {
        tracker->lock();
		result = tracker->validateSession(info->pid, info->sessionId);
        tracker->unlock();
    }

    return result;
}


void BratConnection::trackLogoutSession()
{
    pInfo info = (pInfo)casinoSpecific;

	if (tracker && info && !info->login.isEmpty())
    {
        tracker->lock();
		tracker->logout(ServerOpts::casinoId, info->login, info->forMoney, String::emptyString, info->sessionId);
        tracker->unlock();
    }
}

#else	// USE_SQL

#include <string.h>

#include "lib.h"
#include "bratserv.h"
#include "bratconn.h"
#include "bratver.h"
#include "stdncerr.h"

#define APP1		(uint8)'B'
#define APP2		(uint8)'r'

typedef struct _info
{
	int32 balance;
} Info, *pInfo;

void BratServer::startTracker() { }
void BratServer::stopTracker() { }
bool8 BratServer::initSuccess() { return Server::initSuccess(); }

void
BratConnection::trackaddBadPacket(int32 error_reason, char MessageType, char *msgbuf, int32 msglen) {}

bool8
BratConnection::parseCasinoLogin(int32 /*stdReq*/, int32* Err)
{
	if (msgbuf[1]	!= APP1				|| msgbuf[2] != APP2 ||
		msgbuf[3]	!= PROTO_VERSION1	|| msgbuf[4] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		return false;
	}

	Info* info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	info->balance = 100000;		// $1000.00 to start with

	casinoSpecific = info;

	return true;
}
void
BratConnection::removeCasinoSpecific()
{
	delete (pInfo)casinoSpecific;

	casinoSpecific = (void*)0;
}

int32
BratConnection::encode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
BratConnection::decode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
BratConnection::trackGetBalance()
{
	pInfo info = (pInfo)casinoSpecific;
	if (info)
		return info->balance;
	else
		return 0;
}

int32
BratConnection::trackAdjustBalance(int32 Amount)
{
	pInfo info = (pInfo)casinoSpecific;
	if (info)
	{
		info->balance += Amount;

		return info->balance;
	}
	else
		return 0;
}

bool8
BratConnection::trackGetPlayerLimits(int32* minBet, int32* maxBet)
{
	*minBet = 500;
	*maxBet = 20000;
	return true;
}

bool8
BratConnection::trackGame(BratHand* /*Bank*/, BratHand* /*Player*/,
	int32* /*Bets*/, int32* /*Payouts*/, int32 /*NumBetsPayouts*/,
	int32 /*Commission*/, int32 /*Outcome*/, int32 BalanceAdjust,
	int32* Balance)
{
	pInfo info = (pInfo)casinoSpecific;

	if (info)
		*Balance = trackAdjustBalance(BalanceAdjust);
	else
		*Balance = 0;

	return true;
}

bool8
BratConnection::trackGetOptions(int32 * tiePayout)
{
	tiePayout = (int32) NINE_TO_ONE;
	return true;
}

#endif
